package com.linchong.concurrency.singleton;

import com.linchong.concurrency.annoations.ThreadSafe;

/**
 * @author linchong
 * @version 1.0
 * @Date: 2020-12-08 17:26
 * @Description: SingletonExample1$懒汉模式-volatile+双重同步锁单例模式禁止指令重排序
 * 单例的实例在第一次使用时进行创建
 */
@ThreadSafe
public class SingletonExample5 {
	/**
	 * 私有化构造
	 */
	private SingletonExample5() {

	}

	//单例对象
	private volatile static SingletonExample5 instance = null;

	/**
	 * instance = new SingletonExample4();执行时，
	 * 1.分配对象内存空间，memory=allocate()
	 * 2.初始化对象 ctorInstance()
	 * 3.设置对象指向刚分配的内存 instance=memory
	 *
	 * volatile禁止指令重排序
	 * @return
	 */
	public static SingletonExample5 getInstance() {
		//双重检测机制
		if (instance == null) {
			//同步锁
			synchronized (SingletonExample5.class) {
				if (instance == null) {
					instance = new SingletonExample5();
				}
			}
		}
		return instance;
	}

}
